<template>
  <a-spin class="table-gl-con" style="margin-top: 10px" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <template v-if="!searchParams.isSearchTermProduct">
            <a-button class="gray-outline" size="medium" @click="openAddKeyword" v-if="$authPass('searchTerm.batch.create')">添加到关键词投放</a-button>
            <a-button class="gray-outline" size="medium" @click="batchAddNegativeKeyword" v-if="$authPass('negativeKeyword.create')">添加到否定关键词投放</a-button>
          </template>
          <div>
            <span>已选</span>
            <span class="highlight" style="margin-left: 10px">{{ selectIds.length }}</span>
          </div>
          <a-button type="text" size="medium" @click="clearSelect">清除已选</a-button>
        </a-space>
      </template>
      <template #tableBody>
        <a-table class="table-singe-line" ref="tableRef" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :data="tableList" :scroll="{ x: '100%', y: '100%' }" size="mini" @sorter-change="sorterChange" :pagination="false">
          <template #columns>
            <!-- 搜索词为ASIN -->
            <a-table-column v-if="searchParams.isSearchTermProduct" :width="60" title="图片" data-index="searchAsinImageUrl" key="searchAsinImageUrl" fixed="left">
              <template #cell="{ record }">
                <ImgPopover :src="record.searchAsinImageUrl || record.searchAsinSmallImageUrl" :isPre="true">
                  <template #con>
                    <a-image width="40" :preview="false" height="40" fit="contain" :src="record.searchAsinSmallImageUrl || record.searchAsinImageUrl" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column :width="200" title="买家搜索词" fixed="left">
              <template #title>
                <a-popover>
                  <template #content>
                    <p style="width: 400px">与广告组中关键词匹配的买家搜索词，搜索词是买家在亚马逊上搜索商品时输入的确切词语组合</p>
                  </template>
                  <p>
                    <span>买家搜索词</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <a-typography-paragraph v-if="record.isSearchTermProduct" copyable :copy-text="record.searchAsinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
                  <p class="highlight searchTerm" :class="{ isAdd: record.targetMatchTypeCn }">{{ record.searchTerm }}</p>
                </a-typography-paragraph>
                <p v-else :class="{ isAdd: record.targetMatchTypeCn }" class="searchTerm">{{ record.searchTerm }}</p>
                <p v-if="record.targetMatchTypeCn">
                  <span class="targetMatchTypeCn">{{ record.targetMatchTypeCn }}</span>
                </p>
              </template>
            </a-table-column>
            <a-table-column :width="60" title="趋势图" fixed="left">
              <template #cell="{ record }">
                <i @click="openAdGroupDetail(record)" class="icon icon-tubiao-zhexiantu highlight cursor"></i>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="订单量" align="right" :sortable="sortable" data-index="purchasesOrder" fixed="left">
              <template #title>
                <a-popover content="广告带来的订单及关联订单数量">
                  <p>
                    <span>订单量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="销售额" align="right" :sortable="sortable" data-index="saleAmount" fixed="left">
              <template #title>
                <a-popover content="广告带来的销售额及关联销售额">
                  <p>
                    <span>销售额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos" fixed="left">
              <template #title>
                <a-popover content="投入产出比，ACOS=广告花费/广告销售额*100%">
                  <p>
                    <span>ACOS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="160" title="投放目标" fixed="left">
              <template #cell="{ record }">
                <!-- 商品投放显示 -->
                <div class="flex-c" v-if="record.targetingObjType == 'PRODUCT'">
                  <ImgPopover :src="record.asinImageUrl || record.asinSmallImageUrl" :isPre="true">
                    <template #con>
                      <a-image width="40" :preview="false" height="40" fit="contain" :src="record.asinSmallImageUrl || record.asinImageUrl" />
                    </template>
                  </ImgPopover>
                  <div>
                    <a-typography-paragraph copyable :copy-text="record.asinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
                      <a-button style="line-height: 20px; height: 20px" type="text">{{ record.targeting }}</a-button>
                    </a-typography-paragraph>
                    <p style="color: #999">{{ SearchTermTargetingObjType[record.targetingObjType] || record.targetingObjType }}</p>
                  </div>
                </div>
                <template v-else>
                  <TextLimit :rows="1">{{ record.targeting || '--' }}</TextLimit>
                  <p style="color: #999">{{ SearchTermTargetingObjType[record.targetingObjType] || record.targetingObjType }}</p>
                </template>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="匹配类型">
              <template #cell="{ record }">
                <p v-if="KeywordMatchType[record.matchType]">{{ KeywordMatchType[record.matchType] }}匹配</p>
              </template>
            </a-table-column>
            <a-table-column :width="120" data-index="shopName" title="店铺">
              <template #cell="{ record }">
                <TextLimit>{{ record.shopName }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column :width="100" data-index="portfolioName" title="广告组合">
              <template #cell="{ record }">
                <p :class="props.level ? '' : 'highlight cursor'" @click="toPortfolioDetail(record)">{{ record.portfolioName }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="140" data-index="campaignName" title="广告活动">
              <template #cell="{ record }">
                <TextLimit :class="props.level ? '' : 'highlight cursor'" @click="toCampaignDetail(record)">{{ record.campaignName }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column :width="140" data-index="adGroupName" title="广告组">
              <template #cell="{ record }">
                <TextLimit :class="props.level ? '' : 'highlight cursor'" @click="toAdGroupDetail(record)">{{ record.adGroupName }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column data-index="adType" :width="80" title="活动类型">
              <template #cell="{ record }">
                <p>{{ AdTypes[record.adType] }} </p>
              </template>
            </a-table-column>
            <a-table-column :sortable="sortable" data-index="bid" align="right" :width="100" title="目标竞价">
              <template #title>
                <a-popover content="当此投放触发您的广告时您将为一次点击支付的最高金额">
                  <p>
                    <span>目标竞价</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p>
                  <span>{{ getCurrencySymbol(record.marketplaceId) }}</span>
                  <span>{{ record.bid }}</span>
                </p>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="impressions">
              <template #title>
                <a-popover content="广告曝光次数">
                  <p>
                    <span>曝光量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="clicks">
              <template #title>
                <a-popover content="广告点击次数">
                  <p>
                    <span>点击量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CTR" align="right" :sortable="sortable" data-index="ctr">
              <template #title>
                <a-popover content="广告点击转化率=点击量/曝光量">
                  <p>
                    <span>CTR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="花费" align="right" :sortable="sortable" data-index="cost">
              <template #title>
                <a-popover content="亚马逊广告花费">
                  <p>
                    <span>花费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="CPC" align="right" :sortable="sortable" data-index="cpc">
              <template #title>
                <a-popover content="单次点击成本，CPC=广告花费/点击量">
                  <p>
                    <span>CPC</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CVR" align="right" :sortable="sortable" data-index="cvr">
              <template #title>
                <a-popover content="广告转化率，CVR=广告订单量/点击量*100%">
                  <p>
                    <span>CVR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
              <template #title>
                <a-popover content="单笔订单平均广告花费，CPA=广告花费/广告订单量">
                  <p>
                    <span>CPA</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>

            <a-table-column :width="95" title="商品销量" align="right" :sortable="sortable" data-index="purchasesSale">
              <template #title>
                <a-popover content="广告商品销量">
                  <p>
                    <span>商品销量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
              <template #title>
                <a-popover content="支出回报，ROAS=广告销售额/广告花费">
                  <p>
                    <span>ROAS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- 搜索词详情 -->
  <CampaignDetail showType="searchTerm" v-if="showAdGroupDetail" :defaultSearchVal="searchParams" :currentData="currentData" :isShow="showAdGroupDetail" @closed="showAdGroupDetail = false" />
  <!-- 添加关键词 -->
  <AddKeywordBySearchVal v-if="showAddKeyword" :shopList="shopList" :list="selectRows" :isShow="showAddKeyword" @closed="showAddKeyword = false" @success="getTableList" />
  <!-- 添加否定关键词 -->
  <AddNegativeKeyword v-if="showAddNegativeKeyword" :level="level" type="add" :isShow="showAddNegativeKeyword" :shopList="shopList" :defaultVal="defaultVal" @closed="showAddNegativeKeyword = false" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { searchTermList } from '@/api/advert'
  import CampaignDetail from './campaignDetail.vue'
  import { Message } from '@arco-design/web-vue'
  import { KeywordMatchType, SearchTermTargetingObjType, AdTypes } from '../../types'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import AddNegativeKeyword from './addNegativeKeyword.vue'
  import AddKeywordBySearchVal from './addKeywordBySearchVal.vue'
  import useAdvertStore from '@/store/modules/advert'
  import { useRouter } from 'vue-router'
  import { uuid } from '@/utils'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    level: {
      type: String,
    },
  })
  const emit = defineEmits(['toCampaign'])
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const advertStore = useAdvertStore()
  const tableListMap = ref({})
  const showAddNegativeKeyword = ref(false)
  const showAddKeyword = ref(false)
  const submitLoading = ref(false)
  const showAdGroupDetail = ref(false)
  const defaultVal = ref()
  const currentData = ref<any>({})
  const selectRows = ref<any>([])
  const router = useRouter()
  const tableRef = ref()

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 清除选中
  function clearSelect() {
    tableRef.value.selectAll(false)
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }

  // 获取搜索词数据
  async function getTableList() {
    tableLoading.value = true
    selectIds.value = []
    const res: any = await searchTermList({
      ...props.searchParams,
      ...searchVal.value,
    })
    tableLoading.value = false
    tableRef.value.selectAll(false)
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = uuid()
      tableListMap.value[el.id] = el
    })
  }
  // 显示货币符号
  function getCurrencySymbol(marketplaceId: any) {
    let currency = marketPlaceList[marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }
  // 打开广告详情
  function openAdGroupDetail(row: any) {
    currentData.value = row
    showAdGroupDetail.value = true
  }
  // 进入广告组合
  function toPortfolioDetail(row: any) {
    if (props.level) return
    emit('toCampaign', row)
  }
  // 进入活动详情
  function toCampaignDetail(row: any) {
    if (props.level) return
    changeCampaignIn(row)
    advertStore.changeCurrentLevel('campaign')
    router.push('/advert/campaign/campaignDetail')
    emit('toCampaign', row)
  }
  // 进入广告组详情
  function toAdGroupDetail(row: any) {
    if (props.level) return
    changeCampaignIn(row)
    advertStore.changeGroup({
      adGroupId: row.adGroupId,
      adGroupName: row.adGroupName,
    })
    advertStore.changeCurrentLevel('adGroup')
    router.push('/advert/campaign/campaignDetail')
  }
  function changeCampaignIn(row: any) {
    advertStore.changeShop({
      shopId: row.shopId,
      shopName: row.shopName,
      id: row.shopId,
      marketplaceId: row.marketplaceId,
      sellerId: row.sellerId,
    })
    advertStore.changeCampaignIn({
      campaignId: row.campaignId,
      campaignName: row.campaignName,
      adType: row.adType,
      targetingType: 'AUTO',
      state: row.state,
    })
  }
  // 添加到否定关键词投放
  function batchAddNegativeKeyword() {
    if (!selectIds.value.length) {
      return Message.error('请选择需要添加的搜索词')
    }
    getSelectRows()
    let nameArr = selectRows.value.map((el: any) => el.searchTerm)
    defaultVal.value = nameArr.join('\n')
    showAddNegativeKeyword.value = true
  }
  // 批量添加关键词投放
  function openAddKeyword() {
    if (!selectIds.value.length) {
      return Message.error('请选择搜索词')
    }
    if (selectIds.value.length > 10) {
      return Message.error('一次最多只能添加10个，请分批操作')
    }
    getSelectRows()
    showAddKeyword.value = true
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .normal {
    color: var(--color-text-2);
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
  .isAdd {
    background-color: rgb(var(--warning-2));
  }
  .targetMatchTypeCn {
    background-color: rgb(var(--primary-2));
    display: inline-block;
    margin-top: 3px;
    padding: 0 2px;
  }
  .searchTerm {
    display: inline-block;
    padding: 2px;
  }
</style>
